<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\SignInRequest;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class UserController extends Controller
{

	/**
	 * 注册页面
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function signUp() {
		return view('admin.user.reg');
	}

	/**
	 * 注册处理
	 * @param SignInRequest $request
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function signUpSave(SignInRequest $request) {
		// 调用user model方法注册账号
		$data = $request->all();
		$model = new User();
		$res = $model->reg($data);
		if ($res) {
			// 入session
			//session(['user' => $res]);

			return redirect(null, 200)
				->route('admin.user.login')
				->with($this->createFlash('注册成功,请登录！', 0));
		} else {
			return redirect()
				->back()
				->with($this->createFlash('注册失败！', 1));
		}
	}

	/**
	 * 用户列表
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function list() {
		$logmin = date('Y-m-d');
		$logmax = date('Y-m-d');
		return view('admin.user.list', compact('logmin', 'logmax'));
	}

	/**
	 * 用户列表json
	 * @param Request $request
	 * @return array
	 */
	public function listApi(Request $request) {
		return (new User())->list($request, 'username','created_at');
	}

	/**
	 * 获取一个用户的角色
	 * @param User $user
	 * @return string
	 */
	public function getOne(User $user) {
		$data = $user->with('role')->find($user)->toArray()[0];
		return view('admin.user.one', compact('data'));
	}

	/**
	 * 删除用户
	 * @param $id
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function del(User $user) {
		$res = $user->delete();
		if ($res) {
			return response()->json(['status' => 0, 'msg' => '删除成功']);
		} else {
			return response()->json(['status' => 1, 'msg' => '删除失败']);
		}
	}

	/**
	 * 编辑页
	 * @param int $id
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function edit(int $id) {
		$data = User::with('role')->withTrashed()->find($id);
		$roles = Role::get();
		return view('admin.user.edit', compact('data', 'roles'));
	}

	/**
	 * 编辑提交
	 * @param int $id
	 * @return string
	 */
	public function editSave(Request $request, User $user) {
		$res = $user->update($request->only(['role_id']));
		if ($res) return response()->json(['status' => 0, 'msg' => '修改成功']);
		return response()->json(['status' => 1, 'msg' => '修改失败']);
	}

	/**
	 * 生成闪存消息
	 * @param string $msg 传递的信息
	 * @param int    $status 0为成功 1位失败
	 * @return array
	 */
	private function createFlash($msg, $status) {
		return ['status' => $status, 'msg' => $msg];
	}
}
